# utils/auth.py - 认证工具模块
import base64
import hmac
import hashlib
from urllib.parse import urlencode, urlparse
from datetime import datetime
from time import mktime
from wsgiref.handlers import format_date_time


def assemble_url(request_url, method="POST"):
    """
    生成带鉴权的 URL

    Args:
        request_url: 请求URL
        method: HTTP方法，默认POST

    Returns:
        str: 带认证参数的完整URL
    """
    from config import SPARK_APISecret, SPARK_APIKey

    u = urlparse(request_url)
    host, path = u.hostname, u.path
    date = format_date_time(mktime(datetime.now().timetuple()))
    signature_str = f"host: {host}\ndate: {date}\n{method} {path} HTTP/1.1"
    sign = hmac_sha256(signature_str, SPARK_APISecret)
    authorization = encode_auth_string(SPARK_APIKey, signature_str, sign)
    return f"{request_url}?{urlencode({'host': host, 'date': date, 'authorization': authorization})}"


def hmac_sha256(data, secret):
    """
    生成 HMAC-SHA256 签名并返回 base64 编码

    Args:
        data: 要签名的数据
        secret: 密钥

    Returns:
        str: base64编码的签名
    """
    return base64.b64encode(
        hmac.new(secret.encode(), data.encode(), digestmod=hashlib.sha256).digest()
    ).decode()


def encode_auth_string(apikey, signature_str, signature):
    """
    生成授权头字符串并 base64 编码

    Args:
        apikey: API密钥
        signature_str: 签名字符串
        signature: 签名

    Returns:
        str: base64编码的授权字符串
    """
    auth_str = (
        f'api_key="{apikey}", algorithm="hmac-sha256", '
        f'headers="host date request-line", signature="{signature}"'
    )
    return base64.b64encode(auth_str.encode()).decode()